package com.example.demo.netty.socket;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.internal.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.List;

@Slf4j
public class SocketMessageDecoder extends ByteToMessageDecoder {

    private final Charset charset;

    private int length = 0;

    public SocketMessageDecoder(Charset charset) {
        this.charset = ObjectUtil.checkNotNull(charset, "charset");
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
        log.info("receive client message!","ByteBuf",byteBuf);
        if(byteBuf.readableBytes() >= 4){
            if(length == 0){
                length = byteBuf.readInt();
            }
            if(byteBuf.readableBytes() < length){
                log.info("当前数据不够，继续等待！");
            }else {
                byte[] content = new byte[length];
                if (byteBuf.readableBytes() >= length) {
                    byteBuf.readBytes(content);
                    list.add(new String(content, charset));
                }
                length = 0;
            }
        }
    }
}
